package com.jungle.bfi.generator.util;

import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathUtil {
    private PathUtil() {
    }

    public static void main(String[] args) {
        Path path = Paths.get("com/jungle/bfi/entity/VoucherTypePo.java");
        System.out.println(getFileName(path));
        System.out.println(getFileMainName(path));
        System.out.println(getFileExtension(path));
    }
    public static File getFile(Path path) {
        return path.toFile();
    }

    public static String getFileName(Path path) {
        return path.toFile().getName();
    }

    public static String getFileMainName(Path path) {
        String fileName = getFileName(path);
        int index = fileName.lastIndexOf(".");
        return index > -1 ? fileName.substring(0, index) : fileName;
    }

    public static String getFileExtension(Path path) {
        String fileName = getFileName(path);
        int index = fileName.lastIndexOf(".");
        return index > -1 ? fileName.substring(index + 1) : "";
    }

    public static String getClassPath() {
        URL resource = PathUtil.class.getResource("/");
        assert resource != null;
        return resource.getPath();
    }
    public static Path getProjectPath() {
        URL resource = PathUtil.class.getResource("/");
        assert resource != null;
        Path classPath = Path.of(resource.getPath());
        return classPath.getParent().getParent();
    }

    public static int indexOf(Path path, Path other) {
        int count = path.getNameCount();
        for (int i = 0; i < count; i++) {
            if (startsWith(path, i, other) > -1) {
                return i;
            }
        }
        return -1;

    }

    public static int startsWith(Path path, int from, Path other) {
        Path subpath = path.subpath(from, path.getNameCount());
        return subpath.startsWith(other) ? from : -1;
    }

    public static Path replace(Path source, Path part, Path replace) {
        // 查询替换路径
        int index = indexOf(source, part);
        if (index == -1) {
            return null;
        }
        // 替换为新路径
        Path startPath = source.subpath(0, index);
        Path endPath = source.subpath(index + part.getNameCount(), source.getNameCount());
        return source.getRoot().resolve(startPath).resolve(replace).resolve(endPath);
    }
}
